package com.zheng.cms.rocketmq.rocketmq;




import com.aliyun.openservices.ons.api.*;

import com.aliyun.openservices.ons.api.Producer;
import com.zheng.cms.rocketmq.utils.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;


public class WithdrawMsgProducer {
    private final Logger logger = LoggerFactory.getLogger(WithdrawMsgProducer.class);

    private Producer producer;

    public void init() {

        Properties producerProperties = new Properties();
        producerProperties.setProperty(PropertyKeyConst.ProducerId, CommonConstants.MQ_PID);
        producerProperties.setProperty(PropertyKeyConst.AccessKey, CommonConstants.MQ_AccessKey);
        producerProperties.setProperty(PropertyKeyConst.SecretKey, CommonConstants.MQ_SecretKey);
        producerProperties.setProperty(PropertyKeyConst.ONSAddr, CommonConstants.MQ_ONSAddr);
        producer = ONSFactory.createProducer(producerProperties);
        producer.start();

    }

    public void sendMessage( String text) {
        Message msg = new Message(CommonConstants.MQ_AUTO_TOPIC, CommonConstants.MQ_AUTO_TAG, text.getBytes());
        SendResult sendResult = null;
        try {
            sendResult = producer.send(msg);
            System.out.println("Rule MSG_ID:"+sendResult.getMessageId());
            logger.info("Rule MSG_ID:"+sendResult.getMessageId());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage() + String.valueOf(sendResult));
        }
        // 当消息发送失败时如何处理
        if (sendResult == null) {
            // TODO
        }
    }

    /**
     * Spring bean destroy-method
     */
    public void destroy() {
        producer.shutdown();
    }


}
